/*
 * @Description: 文件内容描述
 * @Author: 李志杰
 * @Date: 2020-04-21 16:42:38
 * @LastEditTime: 2020-05-19 15:45:42
 * @LastEditors: huacong
 */
import _ from 'lodash';
import * as api from '@/services/SupplyPlanMgr';

const hasChildren = (list, item) => {
  let result = false;
  list.forEach(value => {
    if (value.pid === item.id) {
      result = true;
    }
  });
  return result;
};

const getExpandedRowKeys = list => {
  const expandedRowKeys = [];
  _.forEach(list, value => {
    expandedRowKeys.push(value.id);
  });
  return expandedRowKeys;
};

const buildTree = (list, pid = '0') => {
  const tree = [];
  list.forEach(value => {
    const x = value;
    if (x.pid === pid) {
      if (hasChildren(list, x)) {
        x.children = [];
        x.children = buildTree(list, x.id);
      }
      tree.push(x);
    }
  });
  return tree;
};

const Model = {
  namespace: 'VersionComparisonItems',
  state: {
    expandedRowKeys: [],
    items: [],
  },
  effects: {
    *init({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'save',
        payload: { items: [], expandedRowKeys: [] },
      });
      const response = yield call(api.versionCompareDetailUsingGET, payload);
      if (response && response.code === 1 && response.data.length > 0) {
        const { data } = response;
        const expandedRowKeys = getExpandedRowKeys(data);
        const treeData = buildTree(data);
        yield put({
          type: 'save',
          payload: { items: treeData, expandedRowKeys },
        });
      } else {
        callback();
      }
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
export default Model;
